<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入任务名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <!--    <el-card shadow="never">-->
    <!--     <template #header>-->
    <!--        <el-row :gutter="10" class="mb8">-->
    <!--          <el-col :span="1.5">-->
    <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:goods:add']">新增-->
    <!--            </el-button>-->
    <!--          </el-col>-->
    <!--          <el-col :span="1.5">-->
    <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"-->
    <!--                       v-hasPermi="['business:goods:edit']">修改-->
    <!--            </el-button>-->
    <!--          </el-col>-->
    <!--          <el-col :span="1.5">-->
    <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"-->
    <!--                       v-hasPermi="['business:goods:remove']">删除-->
    <!--            </el-button>-->
    <!--          </el-col>-->
    <!--          <el-col :span="1.5">-->
    <!--            <el-button type="warning" plain icon="Download" @click="handleExport"-->
    <!--                       v-hasPermi="['business:goods:export']">导出-->
    <!--            </el-button>-->
    <!--          </el-col>-->
    <!--          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    <!--        </el-row>-->
    <!--      </template>-->

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-if="true" label="任务编号" align="center" prop="goodsId" />
      <el-table-column label="任务名称" align="center" prop="name" />
      <el-table-column label="悬赏图片" align="center" prop="url" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.urlLink" :width="80" :height="80" />
        </template>
      </el-table-column>
      <el-table-column label="悬赏金额" align="center" prop="price" />
<!--      <el-table-column label="任务分类" align="center" prop="type" :formatter="formatType" />-->
      <el-table-column label="任务介绍" align="center" prop="info" />
      <el-table-column label="发布时间" align="center" prop="createTime" />
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="goods_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-popconfirm title="确定要上架吗?" @confirm="handleChangeStatus(scope.row.goodsId, 2)">
            <template #reference>
              <el-button v-if="scope.row.status == 1" link type="primary" size="small">上架</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="确定要下架吗?" @confirm="handleChangeStatus(scope.row.goodsId, 1)">
            <template #reference>
              <el-button v-if="scope.row.status == 2" link type="warning" size="small">下架</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

      <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-tooltip content="修改" placement="top">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                               v-hasPermi="['business:goods:edit']"></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                               v-hasPermi="['business:goods:remove']"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>-->
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    <!--    </el-card>-->
    <!-- 添加或修改任务对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="70%" append-to-body>
      <el-form ref="goodsFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名称" />
        </el-form-item>
<!--        <el-form-item label="任务分类" prop="type">-->
<!--          <el-select v-model="form.type" placeholder="请选择任务分类" clearable>-->
<!--            <el-option v-for="item in typeList" :key="item.businessConfigId" :label="item.configName" :value="item.businessConfigId" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="任务图片" prop="url">
          <image-upload v-model="form.url" />
        </el-form-item>
        <el-form-item label="任务价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入任务价格" />
        </el-form-item>
        <el-form-item label="任务介绍" prop="info">
          <el-input v-model="form.info" placeholder="请输入任务介绍" />
        </el-form-item>
        <el-form-item label="产品详情类型" prop="infoDescType">
          <el-radio-group v-model="form.infoDescType" @change="changeInfoDescType">
            <el-radio value="1">图片</el-radio>
            <el-radio value="2">富文本</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="产品详情">
          <image-upload v-if="form.infoDescType == 1" v-model="form.infoDesc" />
          <editor v-if="form.infoDescType == 2" v-model="form.infoDesc" :min-height="192" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核驳回 -->
    <el-dialog v-model="rejectDialog.visible" title="审核驳回" width="700px" append-to-body>
      <el-form ref="rejectFormRef" :model="rejectForm" :rules="rejectRules" label-width="80px">
        <el-form-item label="驳回原因" prop="infoDesc">
          <el-input v-model="rejectForm.infoDesc" type="textarea" placeholder="请输入驳回原因(必填)" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- 驳回按钮，添加type="danger"来使其显示为红色 -->
          <el-button type="danger" @click="handleReject(rejectFormRef)">驳 回</el-button>
          <el-button @click="rejectDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods" lang="ts">
import { listGoods, getGoods, delGoods, addGoods, updateGoods, updateGoodsStatus, forceShelve } from '@/api/business/goods';
import { getByKeyApi } from '@/api/business/config';
import { GoodsVO, GoodsQuery, GoodsForm } from '@/api/business/goods/types';
import { changeTenantStatus } from '@/api/system/tenant';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { goods_status } = toRefs<any>(proxy?.useDict('goods_status'));

const goodsList = ref<GoodsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
// const typeList = ref([]);

const queryFormRef = ref<ElFormInstance>();
const goodsFormRef = ref<ElFormInstance>();
const rejectFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 定义反馈类型映射
const isUpMap = {
  0: '下架中',
  1: '已上架'
};

const rejectDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const rejectForm = reactive<any>({
  status: 1,
  goodsId: undefined,
  infoDesc: undefined
});
const rejectRules = reactive({
  infoDesc: [{ required: true, message: '请输入驳回原因', trigger: 'blur' }]
});

const initFormData: GoodsForm = {
  goodsId: undefined,
  name: undefined,
  url: undefined,
  price: undefined,
  status: undefined,
  type: undefined,
  info: undefined,
  infoDesc: undefined,
  infoDescType: undefined
};
const data = reactive<PageData<GoodsForm, GoodsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    status: undefined,
    type: undefined,
    params: {}
  },
  rules: {
    goodsId: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
    url: [{ required: true, message: '任务图片id不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '任务价格不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '帐号状态不能为空', trigger: 'change' }],
    type: [{ required: true, message: '任务分类(业务配置表配置id)不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询任务列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGoods(queryParams.value);
  goodsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
const changeInfoDescType = () => {
  form.value.infoDesc = '';
};
// const getByKey = async () => {
//   const res = await getByKeyApi('goods_type');
//   typeList.value = res.data;
// };
// const formatType = (row: GoodsVO, column: any) => {
//   return typeList.value.find((item: any) => item.businessConfigId === row.type)?.configName;
// };
const handleUpdateStatus = async (row: GoodsVO) => {
  let text = row.status === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.name + '"任务吗？');
    await updateGoodsStatus(row.goodsId);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.status = row.status === '0' ? '1' : '0';
  }
};
/** 修改状态 */
const handleChangeStatus = async (id: any, status: any) => {
  // if (status == 1) {
  //   //驳回
  //   rejectForm.status = status;
  //   rejectForm.goodsId = id;
  //
  // } else {
  //
  // }
  let params = {
    goodsId: id,
    status: status
  };
  const res = await updateGoodsStatus(params);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess(res.msg);
    await getList();
  } else {
    proxy?.$modal.msgError(res.msg);
  }
};
/** 驳回 */
const handleReject = async (formEl: ElFormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      updateGoodsStatus(rejectForm).then((res) => {
        if (res.code === 200) {
          proxy?.$modal.msgSuccess(res.msg);
          rejectDialog.visible = false;
          rejectFormRef.value?.resetFields();
          getList();
        } else {
          proxy?.$modal.msgError(res.msg);
        }
      });
    }
  })
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  goodsFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: GoodsVO[]) => {
  ids.value = selection.map((item) => item.goodsId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加任务';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: GoodsVO) => {
  reset();
  const _goodsId = row?.goodsId || ids.value[0];
  const res = await getGoods(_goodsId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改任务';
};

/** 强制下架 */
const handleForceShelve = async (row?: GoodsVO) => {
  reset();
  const _reportId = row?.goodsId || ids.value[0];
  await forceShelve(_reportId).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

/** 提交按钮 */
const submitForm = () => {
  goodsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.goodsId) {
        await updateGoods(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addGoods(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: GoodsVO) => {
  const _goodsIds = row?.goodsId || ids.value;
  await proxy?.$modal.confirm('是否确认删除任务编号为"' + _goodsIds + '"的数据项？').finally(() => (loading.value = false));
  await delGoods(_goodsIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/goods/export',
    {
      ...queryParams.value
    },
    `goods_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  // getByKey();
});
</script>
